package ru.ifmo.network.skype.network;

import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;

/**
 * @author avhaliullin
 */
public class NetworkUtils {
    public static void readFull(InputStream in, byte[] buf) throws IOException {
        int len = buf.length;
        int offset = 0;
        while (offset < len) {
            int res = in.read(buf, offset, len - offset);
            if (res >= 0) {
                offset += res;
            } else {
                throw new EOFException("EOF found while reading stream");
            }
        }
    }

    public static void writeShort(short v, byte[] buf, int offset) {
        ByteBuffer bb = ByteBuffer.wrap(buf, offset, 2);
        bb.order(ByteOrder.LITTLE_ENDIAN).asShortBuffer().put(0, v);
    }

    public static short readShort(byte[] buf, int offset) {
        return ByteBuffer.wrap(buf, offset, 2).order(ByteOrder.LITTLE_ENDIAN).asShortBuffer().get(0);
    }

    public static void writeInt(OutputStream out, int v) throws IOException {
        ByteBuffer bb = ByteBuffer.allocate(4);
        bb.order(ByteOrder.LITTLE_ENDIAN).asIntBuffer().put(0, v);
        out.write(bb.array());
    }

    public static int readInt(InputStream in) throws IOException {
        byte[] bb = new byte[4];
        readFull(in, bb);
        return ByteBuffer.wrap(bb).order(ByteOrder.LITTLE_ENDIAN).asIntBuffer().get(0);
    }

    public static void writeShort(OutputStream out, short v) throws IOException {
        ByteBuffer bb = ByteBuffer.allocate(2);
        bb.order(ByteOrder.LITTLE_ENDIAN).asShortBuffer().put(0, v);
        out.write(bb.array());
    }

    public static short readShort(InputStream in) throws IOException {
        byte[] bb = new byte[2];
        readFull(in, bb);
        return ByteBuffer.wrap(bb).order(ByteOrder.LITTLE_ENDIAN).asShortBuffer().get(0);
    }
}
